<!--vue模板-->
<template>
  <el-dialog @close="close" v-model="visible" :close-on-click-modal="false" 
    :title="ruleForm.id?'更新用户':'添加用户'" width="60%" draggable>

    <!-- 表单数据 -->
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="ruleForm" status-icon>

      <el-form-item label="登录账号" prop="account">
        <el-input v-model="ruleForm.account" :disabled="ruleForm.id?true:false" class="ipt" placeholder="请输入登录账号" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" disabled placeholder="默认密码666666" class="ipt" />
      </el-form-item>

      <el-form-item label="账号生效日期" prop="effectiveDate">
        <el-date-picker v-model="ruleForm.effectiveDate" type="date" placeholder="请选择账号激活日期" value-format="YYYY-MM-DD"
          size="default" />
      </el-form-item>

      <el-form-item label="备注" prop="note">
        <el-input v-model=" ruleForm.note " class="ipt" placeholder="请输入备注信息" :rows=" 5 " type="textarea" />
      </el-form-item>

      <el-form-item label="员工编号" prop="eid">
        <el-input v-model=" ruleForm.eid " disabled placeholder="请选择" class="ipt" />
      </el-form-item>

      <el-form-item label="真实姓名" prop="name">
        <el-input v-model=" ruleForm.name " class="ipt" placeholder="请输入真实姓名" />
      </el-form-item>

      <el-form-item label="角色" prop="roles">
        <el-input v-model=" ruleForm.roles " class="ipt" placeholder="请输入用户角色" />
      </el-form-item>

      <el-form-item label="签名照片" prop="signUrl">
        <el-upload class="avatar-uploader" :action="uploadUrl"
          :show-file-list=" false " :on-success=" handleAvatarSuccess " :before-upload=" beforeAvatarUpload ">
          <img v-if=" imageUrl " :src=" imageUrl " class="avatar" style="width: 300px;" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>



    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click=" saveUser ">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<!--vue 组件选项定义-->
<script setup>
import { inject, reactive, ref } from 'vue'

import userApi from '@/api/UserApi.js'
import Schema from 'async-validator';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import host from "@/util/DEV_ADDRESS";




// 定义文件的上传路径
const uploadUrl = ref(host + 'upload')

// 父组件控制数据的显示
const visible = inject('visible')





// 图片上传
const imageUrl = ref('')

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  ruleForm.value.signUrl = response.data
  console.log(response,"图片上传");
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!')
    return false
  }
  return true
}


const ruleFormRef = ref(null)



// 表单
const ruleForm = ref({
  account: '',
  effectiveDate: '',
  signUrl: '',
  note: '',
  eid: '',
  name: '',
  roles: ''
})

// 清空表单方法
const clearForm = () => {
  ruleForm.value = {
    account: '',
    effectiveDate: '',
    signUrl: '',
    note: '',
    eid: '',
    name: '',
    roles: ''
  }
  imageUrl.value = ''
  console.log('清空表单方法执行 clearForm');
}

// 初始化数据信息
const initUser = (userInfo) => {

  // 赋值
  ruleForm.value = userInfo
  imageUrl.value = userInfo.signUrl

}

defineExpose({ initUser,clearForm }); //  {"init":init}




// 暴露接口


// -------------定义异步检测

const cn = {
  required: '%s 已被占用！'
}

const descriptor = {
  account: {
    type: 'string',
    asyncValidator: (rule, value) => {
      return new Promise(async (resolve, reject) => {
        if (ruleForm.value.account.length > 0) {
          const res = await userApi.checkAccount(ruleForm.value.account)
          // 如果账号被占用 这里判断为更新 或者添加
          if (!res.data && !ruleForm.value.id ) {
            reject('该账号已被占用！');  // reject with error message
          } else {
            resolve();
          }
        } else {
          reject('请输入要注册的账号！');
        }
      });
    },
  },
};

const validator = new Schema(descriptor)
validator.messages(cn)

// 异步检查账号是否唯一
const validatorAccount = (rule, value, callback) => {
  console.log(rule, value, callback);
  validator.validate(ruleForm.value.account).then(() => {
    // validation passed or without error message
    callback()
  }).catch(({ errors, fields }) => {
    callback(new Error(errors[0].message))
  });
}

//  表单校验规则
const rules = reactive({
  account: [
    { validator: validatorAccount, trigger: 'blur' }
  ]
})

const emit = defineEmits(['close'])

function close() {
  visible.value = false
    // 重置表单 去除之前的校验
    ruleFormRef.value.resetFields()
  emit('close')
}


// 保存用户信息
const saveUser = () => {
  ruleFormRef.value.validate(val => {
    console.log(val, "val");
    if (val) {
      // 更新用户
      if(ruleForm.value.id) {
        console.log("更新用户！");
        userApi.updateUserById(ruleForm.value).then(resp => {
            ElMessage({
              type: 'success',
              message: '更新成功',
            })

            close()
          })
      }else {
              // 添加用户
          userApi.insertUser(ruleForm.value).then(resp => {
            ElMessage({
              type: 'success',
              message: '添加成功！',
            })

            close()
          })
      }
    }
  })
}




</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.ipt {
  width: 90%;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>